package cn.huhaoran.yaoyaolingxian.ui.CustomTreeTableImpl;

import org.jdesktop.swingx.treetable.AbstractTreeTableModel;

import javax.swing.tree.TreePath;

public class GitBranchTreeTableModel extends AbstractTreeTableModel {
    private final String[] columnNames = {"分支", "分支全名", "最后一次提交的Hash值", "导入后的分支名"};

    public GitBranchTreeTableModel(GitBranchNode root) {
        super(root);
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public Object getValueAt(Object node, int column) {
        GitBranchNode branchNode = (GitBranchNode) node;

        switch (column) {
            case 0:
                return branchNode.isSelected(); // 返回选中状态
            case 1:
                return branchNode.getFullBranchName();
            case 2:
                return branchNode.getBranchHash();
            case 3:
                // 如果是目录节点，返回 null
                return branchNode.isLeaf() ? CreateGitBranchTreeTableUtils.processBranchName(branchNode.getEditableName())  : null;
            default:
                return null;
        }
    }

    @Override
    public void setValueAt(Object value, Object node, int column) {
        GitBranchNode branchNode = (GitBranchNode) node;
        switch (column) {
            case 3:
                branchNode.setEditableName((String) value);
                break;
        }
        // 获取节点路径并触发更新
        TreePath path = new TreePath(branchNode.getPath());
        modelSupport.firePathChanged(path);
    }

    @Override
    public boolean isCellEditable(Object node, int column) {
        GitBranchNode branchNode = (GitBranchNode) node;
        // 禁用目录节点的编辑功能
        if (column == 3 && !branchNode.isLeaf()) {
            return false;
        }
        // 其他情况下按默认处理
        return column == 3;
    }

    @Override
    public Object getChild(Object parent, int index) {
        return ((GitBranchNode) parent).getChildAt(index);
    }

    @Override
    public int getChildCount(Object parent) {
        return ((GitBranchNode) parent).getChildCount();
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        return ((GitBranchNode) parent).getIndex((GitBranchNode) child);
    }

    @Override
    public Class<?> getColumnClass(int column) {
        return column == 0 ? Boolean.class : super.getColumnClass(column); // 第一列是 Boolean 类型，但不用于编辑
    }
}
